import express, {Request} from 'express'
import process from 'process'
import fs from 'fs-extra'
import path from 'path'
import { EdgeTTS } from 'node-edge-tts'
import { generateVideo, transformLines, translateLines } from './helper'

const app = express()
const port = 3001
const cwd = process.cwd()

console.log({ cwd })

//设置跨域访问
app.all('*', function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*')
  // //允许的header类型
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
  // //跨域允许的请求方式
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  // 可以带cookies
  res.header('Access-Control-Allow-Credentials', 'true')
  if (req.method == 'OPTIONS') {
    res.sendStatus(200)
  } else {
    next()
  }
})

app.use('/static', express.static(path.join(cwd, 'static')))

app.get('/genemp3', (req, res) => {
  const timestamp = Date.now()
  const fileName = `${timestamp}/audio.mp3`
  const target = path.join(cwd, `static/${fileName}`)
  const tts = new EdgeTTS({
    saveSubtitles: true
  })
  fs.ensureFileSync(target)

  tts
    .ttsPromise(req.query.text as string, target)
    .then(() => {
      const jsonFilePath = path.join(`${target}.json`)
      // 根据生成的语音给文章分成句子
      const sublines = transformLines(jsonFilePath)
      translateLines(sublines).then((transed) => {
        generateVideo({
          audio: target,
          lines: transed,
          cwd,
          folderName: path.join(cwd, 'static',`${timestamp}`)
        })
        res.send({
          transed,
          audio: fileName
        })
      })

      // res.send(fileName)
    })
    .catch((e) => {
      console.log(e)
    })
})

export function startServer(): void {
  app.listen(port, () => {
    console.log(`text2video app listening on port ${port}`)
  })
}

startServer()